package mwm.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import mwm.server.moveresize.MoveResize;
import mwm.server.switcher.Switcher;

public class Main {
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e1) {
		} catch (InstantiationException e1) {
		} catch (IllegalAccessException e1) {
		} catch (UnsupportedLookAndFeelException e1) {
		}
		if (args.length != 1) {
			usage();
			System.exit(1);
		}

		int port = 0;
		try {
			port = Integer.parseInt(args[0]);
			if (port <= 1024 || port >= 65536) {
				usage();
				System.exit(1);
			}
		} catch (NumberFormatException nfe) {
			usage();
			System.exit(1);
		}
		
		try {
			new Server(port).start();
		} catch (NumberFormatException nfe) {
			usage();
			System.exit(-1);
		}
	}

	private static void usage() {
		System.err.println("Usage: java -jar MWMServer.jar port");
		System.err.println("where: 1024 < port < 65536");
	}
	
	private static class Server extends Thread {
		private final int port;

		Server(int port) {
			this.port = port;
		}
		
		public void run() {
			try {
				ServerSocket serverSocket = new ServerSocket(port, 2);
				while (true) {
					final Socket socket = serverSocket.accept();
					new Thread(new Runnable() {
						public void run() {
							serve(socket);
						}
					}).start();
				}
			} catch (IOException e) {
				System.err.println(e.getMessage());
			}
		}
	}
		
	private static void serve(Socket socket) {
		InputStream in = null;
		PrintWriter out = null;
		try {
			in = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String input = br.readLine();
			if (input == null) {
				return;
			}
			if ("exit".equals(input)) {
				System.exit(0);
			} else if (input.startsWith("moveresize ")) {
				input = input.substring(11);
				out = new PrintWriter(socket.getOutputStream());
				try {
					MoveResize.moveresize(input, out);
				} catch (IllegalArgumentException iae) {
				}
			} else if (input.startsWith("switcher ")) {
				input = input.substring(9);
				out = new PrintWriter(socket.getOutputStream());
				try {
					Switcher.show(input.split("@@@@"), out);
				} catch (IllegalArgumentException iae) {
				}
			}
		} catch (IOException e) {
			System.err.println(e.getMessage());
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
			try {
				socket.close();
			} catch (IOException e1) {
			}
		}
	}
}
